module UtilHelper

  def boton_plegar(tipo,id,is_a_mod=false)
    jqplegar= is_a_mod ? {:text=>"Plegar/Desplegar todos",:action=>"$('li.#{tipo}_#{id}').toggle();" }: {:text=>'(+/-)',:action=>"$('li##{tipo}_#{id}').toggle();"}
    html=<<HTML
    <small>#{link_to_function jqplegar[:text], jqplegar[:action]}</small>
HTML
    html
  end

  def expandir_modulo(m,perfil,father=nil,show=false)
    html=''
    check_box_action="$('ul#modulo_#{m.id} input:checkbox').attr('checked', $(this).attr('checked'));"
    events={:onclick=>check_box_action,:disabled=>show,:class=>father,:id => "modulo_#{m.id}"}
    father ? events.merge!({:onchange=>"check_padre($(this),$('input#'+'#{father}'))"}) : html+=check_padre
    check_box=check_box_tag "perfil[modulo_ids][]",m.id,perfil.modulos.include?(m),events
    html+="<ul id=modulo_#{m.id} class=#{father}>"
    #html+="<b style='color:green'>#{check_box} #{m.nombre}:</b> #{m.descripcion}#{print_a_button?(m,father)}"
    html+="<b style='color:green'>#{check_box} #{m.nombre}:</b> #{m.descripcion}#{boton_plegar("modulo",m.id)}"
    m.submodulos.each do |sm|
      html+="<li id='modulo_#{m.id}' class=#{father}>"
      html+=expandir_modulo(sm,perfil,"#{father} modulo_#{m.id}",show)
      html+="</li>"
    end
    m.controlleres.each do |c|
      html+="<li id='modulo_#{m.id}'>"
      html+="<b>#{c.nombre}:</b> #{c.descripcion}#{boton_plegar("controller",c.id)}" if c.modulo.modulo_id.nil?
      html+=expandir_controller(c,"#{father} modulo_#{m.id}",show)
      html+="</li>"
    end
    html+="</ul>"
    if father.nil?
      html="<div class='pane'>#{html}</div>"
    end
    html
  end

  def expandir_controller(c,father,show)
    html="<ul class='controller_#{c.id}'>"
    event="check_padre($(this),$('input#'+'#{father}'))"
    c.acciones.each do |a|
      html+="<li id='controller_#{c.id}' class='#{father}'>"
      html+="<b>#{a.nombre}:</b> #{a.descripcion}#{check_box_tag 'perfil[accion_ids][]',a.id,@perfil.acciones.include?(a),:class => father,:disabled=>show,:onchange=>event}"
      html+="</li>"      
    end
    html+="</ul>"
    html
  end

  def check_padre
    html=<<HTML
    <script type="text/javascript">
    function check_padre(son,father){
      if (!father.attr('checked') && son.attr('checked')){
          father.attr('checked',true);
          if (father.attr('class')!=""){
            check_padre(father,$('input#'+father.attr('class')))
          }
      };
    };
</script>
HTML
    html
  end

  def print_a_button?(m,father)
    b1=boton_plegar("modulo",m.id)
    b2="<li id='modulo_#{m.id}'class='#{father}'>#{boton_plegar('modulo',m.id,true)}"
    (m.submodulos.count>0 or m.controlleres.count>0)? "#{b1}#{b2}" : ""
  end

  def self.mes_nombre(numeroMes)
    (1..12)===numeroMes.to_i ? I18n.translate(:date)[:month_names][numeroMes.to_i] : "No existe el mes #{numeroMes}."
  end

  #Formato standard para el proyecto
  def sino(campo, verdad = false,nil_as_false=true)
    return campo if campo.nil? and !nil_as_false
    if verdad
      campo == true ? "Verdadero" : "Falso"
    else
      campo == true ? "Si" : "No"
    end
  end

  def sino_options_for_select(si_as_false=false)
    si_as_false ? {"Si"=>false,"No"=>true } :{"Si"=>true,"No"=> false}
  end

  def tabular_form_for(name, object, options, &proc)
    options[:html] ||= {}
    options[:html][:class] = 'tabular' unless options[:html].has_key?(:class)
    form_for(name, object, options.merge({ :builder => TabularFormBuilder, :lang => current_language}), &proc)
  end

  def print(display_label, data)
    "<p><b>#{display_label}:</b> #{data}</p>"
  end
  #Muestra el nombre equivalente a un codigo en un vector
  def mostrar(valor, vector)
    val = vector.index(valor)
    val ? val.to_s : ""
  end
  #Muestra la edad
  def edad(fecha)
    if fecha
      edad=fecha.nil? ? 0 : ((Date.today - fecha).to_i / 365)
      ((Time.now.month==fecha.month and Time.now.day>=fecha.day) or (Time.now.month>fecha.month))  ? edad : edad-1
      edad.to_s + ' ' + "a&ntilde;os"
    else
      "N/A"
    end
  end

  #Crea todo lo necesario para armar los tabs
  # Ejemplo
  # tabs [{:nombre => "Datos", :url => "#"}, {:nombre => "Direcciones", :url => persona_direccion_path(@persona, :_window => true)}

  def tabs(id, tabs)
    html = <<HTML
<script>
$(function() {
	$("##{id}").tabs("##{id} > div.pane", function(i){
    var pane = this.getPanes().eq(i);
    var tab = this.getTabs().eq(i);
    if (pane.is(":empty")) {
      pane.load(tab.attr("href"));
    }
  }
  );
});
</script>
<div class="smalltabs" id="#{id}">
<ul>
HTML
    tabs.each do |tab|
      html << "<li><a href='#{tab[:url]}' title='#{tab[:nombre]}'><span> #{tab[:nombre]}</span></a></li>"
    end
    html << "</ul> </div>"
    html
  end
  
  def menu_item(nombre, opts={})
    opts[:link]||={}
    opts[:tag]||="li"
    opts[:link][:action]||= "index"
    opts[:link][:controller]||=nombre.downcase
    resultado = ""
    opts[:ignore_action]||= []
    opts[:controls] ||=  [nombre.downcase]
    opts[:imagen] ||= nombre.downcase
    clase=(opts[:controls].include?(controller_name) and !opts[:ignore_action].include?("#{controller_name}:#{action_name}")) ? "selected" : nil
    resultado = "<#{opts[:tag]}> #{boton(nombre, opts[:link],:imagen=>opts[:imagen], :class => clase)} </#{opts[:tag]}>"
    resultado 
  end

  def tabla(columnas, datos,opts={:tclass=>"tabla-centrada",:colw=>"20%"}, &block)
    html = <<HTML
      <table class="#{opts[:tclass]}">
      <thead>
        <tr>
HTML
    concat(html)
    columnas.each{|col| concat("<th width='#{opts[:colw]}'>#{col}</th>")}
    color="even"
    concat("</tr></thead><tbody>")
    datos||=[]
    method = datos.first.is_a?(Array) ? :datos_tabla_array : :datos_tabla_obj
    datos.each do |categoria|
      self.send(method,categoria,color)
       color=get_next_class(color)
      yield categoria
      concat("</tr>")
    end
    concat("</tbody></table>")
  end
  
  def submenu_item(nombre, opts={})
    opts[:imagen] ||= nombre.downcase# + ".png"
    opts[:controller] ||= nombre.downcase
    opts[:action_name] ||= "Agregar"
    opts[:action] ||= :new
    path1={:controller => opts[:controller], :action => :index}
    path2={:controller => opts[:controller], :action => opts[:action]}
    html = <<HTML
      <p>
        #{boton nombre,path1,:imagen=>opts[:imagen] } -
        #{boton opts[:action_name],path2,:imagen=>opts[:action_name]}
      </p>
HTML
    html
  end

  def format_time_fields(opts={})
    opts[:fieldClass]   ||="timeEntry"
    opts[:show24Hours]  ||= true
    opts[:useMouseWheel]||= true
    opts[:appendText]   ||="''"
    html = <<HTML
    #{stylesheet_link_tag "jquery.timeentry.css"}
    #{javascript_include_tag "jquery.mousewheel.min.js"}
    #{javascript_include_tag "jquery.timeentry.min.js"}

    <script>
      function formatTimeFields() {
        $('.#{opts[:fieldClass]}').timeEntry({show24Hours:#{opts[:show24Hours]},
                                              useMouseWheel:#{opts[:useMouseWheel]},
                                              appendText:#{opts[:appendText]},
                                             });
      }
      $(document).ready(function(){formatTimeFields()});
    </script>
HTML
    html
  end

  def format_money_fields(opts={})
    opts[:fieldClass]||="money"
    opts[:mDec]||= 0
    opts[:aSep]||= "."
    opts[:aDec]||= ","
    html = <<HTML
    <script>
      $(function() {
        $('.#{opts[:fieldClass]}').autoNumeric({mDec:#{opts[:mDec]},aSep:"#{opts[:aSep]}",aDec:"#{opts[:aDec]}"});
        
        $('.#{opts[:fieldClass]}').each(function(){
		
		$(this).focus(
		function(){
				var s =$.fn.autoNumeric.Format(this.id,this.value,{mDec:#{opts[:mDec]},aSep:"#{opts[:aSep]}",aDec:"#{opts[:aDec]}"})
				this.value=s
			});

			$(this).blur(function(){
				var s=$.fn.autoNumeric.Strip(this.id,{mDec:#{opts[:mDec]},aSep:"#{opts[:aSep]}",aDec:"#{opts[:aDec]}"})
				this.value=s
			});
        })
        
      })
    </script>
HTML
    html
  end

  def format_multiselect_fields(opts={})
    html = <<HTML
      #{javascript_include_tag "jquery.multiselect.js"}
      #{stylesheet_link_tag("jquery.multiselect.css")}
      <script type="text/javascript">
      #{opts[:id]} = [#{opts[:options].collect{|o| o.nombre.inspect+","}}]
    $(function() {
    $("##{opts[:id]}").multiselect({completions: #{opts[:id]}});
    });
    </script>
HTML
    html
  end
  #Depende de jquery.js,datepicker.js
  def format_date_fields(clase='dp')
    html = <<HTML
    <script type="text/javascript">
      $(document).ready(function(){
        formatDateFields('#{clase}');
      });
    </script>
HTML
    html
  end

  def validate_forms()
    html = <<HTML
    <script type="text/javascript">
      $(document).ready(function(){
        validateForms();
      });
    </script>
HTML
    html
  end

 def default_cbox_ajax_form_opts
   {:complete =>"$.colorbox.close()", :condition => '$(this).valid()'}
 end
 

 def default_form_builder
   {:html => {:class => "tabular"},:builder => UniformBuilder}
 end
 
  def readonly?(field)
    field.nil? ? "" : {:readOnly=>"true"}
  end
end

private

def datos_tabla_array(categoria,class_actual)
  concat("<tr id='tr-#{categoria[0].class.name.downcase}-#{categoria[0].id}' class=#{class_actual}>")
end

def datos_tabla_obj(categoria,class_actual)
  concat("<tr id='tr-#{categoria.class.name.downcase}-#{categoria.id}' class=#{class_actual}>")
end

def get_next_class(class_actual)
  class_actual=="even" ? "odd" : "even"
end
